<template>
    <!-- 我的工作 -->
  <workStatistics :todayData="today"></workStatistics>
  
  <zsearch  v-loading="loading">
    <template #tabs>
      <!-- <zbagerbtn 
        :totalNum="totalNum" 
        :bagerTitle="bagerTitle"
        @handleStatusSearch="handleStatusSearch"
        ></zbagerbtn> -->
    </template>
    <template #title>
      <span>今日就诊</span>
    </template>
      <template #date>
        <el-date-picker
            class="date-6"
            type="date"
            v-model="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            >
        </el-date-picker>
        <zbagerbtn 
          :totalNum="totalNum" 
          :bagerTitle="bagerTitle"
          @handleStatusSearch="handleStatusSearch"
          ></zbagerbtn>
      </template>
      <template #select>
        
        <el-input class="input-2" v-model="name" @input="inputValue" placeholder="患者/手机/病历号"></el-input>
        <el-select class="select-3" v-model="doctorId" clearable filterable placeholder="选择医生">
          <el-option
            v-for="item in optionsDoctor"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
        <el-select class="select-3" v-model="secondaryUserId" clearable filterable placeholder="选择咨询师">
          <el-option
            v-for="item in optionsSecondaryUser"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
        <el-select class="select-3" v-model="detailType" clearable filterable placeholder="选择就诊类型">
          <el-option
            v-for="item in detailTypeList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </template>
      <template #btns>
        <el-button class="btn-1" :loading="loading" @click="hanledSearch">查询</el-button>
	      <el-button class="btn-2">导出</el-button>
      </template>
      <template #table>
        <ztable 
          :tableData='data' 
          :strucs='columns'
          :height="'100%'"
          :width="'240'"
          @editRegister="editRegister"
          @editAppoiment="editAppoiment"
          @cancelAppoiment="cancelAppoiment"
          @addNewAppoiment="addNewAppoiment"
          @handleRegister="handleRegister"
          @startTreatment="startTreatment"
          @overTreatment="overTreatment"
          @handleClickReturnOpeation="handleClickReturnOpeation"
          @leave="leave"
          @goCharge="goCharge"
          @onToDetail="onToDetail"
        ></ztable>
      </template>
      <template #page>
        <zpage 
            :currentPage="current" 
            :total="total"
            :pageSize="size"
            @handleSizeChange="handleSizeChange" 
            @handleCurrentChange="handleCurrentChange"
        ></zpage>
      </template>
    </zsearch>

  <!-- 取消预约 -->
  <zdialog title="取消预约" @handleClose="closeDialog" v-model="dialogVisible" :btnData="dialogBtnData">
      <template #body>
        <div class="person-info">
          <span>患者: <span class="name">{{ personName}}</span></span>
          <span>预约时间: {{subscribeTime}}</span>
        </div>
			</template>
  </zdialog>

  <!-- 新增/挂号/ 预约/  -->
  <el-drawer
			size="45%"
			:title="title"
			v-model="showDrawer"
			:before-close="drawerClose" destroy-on-close>
			<zaddpatient 
					@cancel="cancel" 
					@saveMakeAnAppointment="saveMakeAnAppointment" 
					@saveAndRegister="saveAndRegister"
					v-if="isADD === 'add'"
					></zaddpatient>
		
			<zregister v-if="isADD === 'register'"
				@cancel="cancel" 
				@handlebtn="handlebtn"
        @reloadList="reloadList"
        @clickRegisterStatus="clickRegisterStatus"
        :registerInfo="registerInfo"
        :userId="userId"
				></zregister>

			<zmakeanapp v-if="isADD === 'makeanapp'"
				@handlebtn="handlebtn"
				@cancel="cancel"
        @reloadList="reloadList"
        :makeanappInfo="makeanappInfo"

				></zmakeanapp>
	</el-drawer>

</template>

<script lang='ts'>
import { defineComponent, reactive, toRefs, ref, inject, onMounted, watch } from '@vue/runtime-core'

import useRequet, { RespData } from "../../hook/network"
import { Option, WsMessageType } from "../../types/index"

import useConfgin from '../../hook/getconfig'

import ztable from '@components/Table/index.vue'
import zpage from '@components/pagination/pagination.vue'
import zsearch from '@components/search/search.vue'
import zdialog from '@components/dialog/dialog.vue'
import zbagerbtn from '@components/bagerbtn/bagerbtn.vue'

import zmakeanapp from "../../components/patient/makeAnAppointment.vue"
import zaddpatient from "../../components/patient/add.vue"
import zregister from "../../components/patient/register.vue"

import workStatistics from "../../components/workStatistics/work.vue"

import { useRoute, useRouter } from "vue-router"

// 详情添加患者
import useSetAddLog from "../../hook/setAddLog"
import useRequest from '../../hook/request'
import { getNowDate } from '../../utils/nowDate'
import { getDoctors, getConsultant } from '../../usefn/getDoctor'
import { getDoctorListAllAPi, getConsultListAllAPi } from '../../api/common'
import { debounce } from "../../utils/debounce"
// 得到数量
import { getAllRecord, getRecordArrived, getRecordNoArrived } from "../../usefn/getNumner"
import { getTimeminute } from "../../usefn/getBirthday"

import { ElMessage, ElMessageBox } from 'element-plus'
import { useWebSocket } from "../../hook/websocket"
import store from '../../store'
import useUser from "../../hook/user";

import eventBus from 'vue3-eventbus';

const configID = 527
export default defineComponent({
  name: 'DoctorToday',
  components: {
    ztable,
    zpage,
    zsearch,
    zdialog,
    zbagerbtn,

    zmakeanapp,
    zaddpatient,
    zregister,

    workStatistics,
  },
  setup() {
    const user = useUser();
    console.log(user.id)
    let search = reactive({
      date: window.localStorage.getItem('toDaySearchTimeCache') || getNowDate(),
      name:'',
      current: 1,
      size: 30,
      total: 0,
      comeStatus: null,

      doctorId: null,
      secondaryUserId: null,
      detailType: '',
      optionsDoctor: [] as Option[],
      optionsSecondaryUser: [] as Option[],
      detailTypeList: [
        {
          id: '初诊',
          name: '初诊'
        },
        {
          id: '复诊',
          name: '复诊'
        }
      ],

      loading: false
    })

    watch(() => search.date, (newV) => {
      console.log(newV, "改变了哦")
      if(newV) {
        window.localStorage.setItem('toDaySearchTimeCache', newV)
      }
    })
    let today = reactive({
      todayNewCustomer: 0,
      todayNewSub: 0,
      todayNewCollection: 0,
      todayNewAccessLog: 0,
      todayNewSickMedicalRecords: 0
    })
    
    const router = useRouter()
    const data = ref([])
    const { groupDataList } = useConfgin(configID)
    let columns = groupDataList.value

    const request = useRequet({ path: "" });
    const refreshList = () => {
      req()
    }
    eventBus.on('refreshList', refreshList)
    
    
    const req = async() => {
      search.loading = true
      
      let params = {
        comeStatus: search.comeStatus,
        customerQueryValue: search.name,
        day: search.date,
        doctorId: search.doctorId,
        secondaryUserId: search.secondaryUserId,
        current: search.current,
        size: search.size,
      } as any
      if(search.detailType) {
        params.detailType = search.detailType
      }
      await useRequest('sick/record/getTodayRecordPage/', params, 'POST').then((res: any) => {
        if(res.code !== 0)  return ElMessage.error('列表获取' + res.msg)

        data.value = res.data.records
        data.value.forEach((i:any, index) => {
          i.startTime = getTimeminute(i.startTime)
          i.index = ++index
        })
        search.total = res.data.total
        search.current = res.data.current

        search.loading = false
      }).catch(e => {
        return ElMessage.error('列表获取' + e.msg)
      })
      
    }

    const handleMessage = (e: Event | any) => {
      // 接收后端广播回来的数据
      let obj:WsMessageType = JSON.parse(e.data)
      console.log(typeof obj.data)
      if(obj.messageType === 'REFRESH_COUNT') {
        switch(Number(obj.data)) {
          case 1:
            getNumber()
            break
        }
        
      }
    }
    const ws = useWebSocket(handleMessage)
    
    const handleStatusSearch = (type: string) => {
      let obj = {
        'All': null,
        'Arrived': true,
        'NotArrived': false
      }
      search.comeStatus = obj[type]
      req()
    }

    let totalNum = reactive({
      total: 0,
      arrived: 0,
      notArrived: 0
    })

    let bagerTitle = {
      labelone: '全部',
      labeltwo: '已到',
      labelthree: '未到'
    }

    // 得到数量
    const getNumber = () => {
      getAllRecord().then(res => {
        totalNum.total = res
      })
      
      getRecordArrived().then(res => {
        totalNum.arrived = res
      })
      getRecordNoArrived().then(res => {
        totalNum.notArrived = res
      })
    }
    

    const getListValue = () => {
      console.log('处理接口方法调用')
    }

    const debounceInput = debounce(getListValue, 1000)
    const inputValue = (e: string) => {
      debounceInput()
    }
    

    const getTodayStatistics = async() => {
      let result:any = await useRequest('/pay/order/todayStatistics', {}, 'POST')
      if(result.code !== 0) return ElMessage.error('数据获取' + result.msg)
        today.todayNewCustomer = result.data.todayNewCustomer
        today.todayNewSub = result.data.todayNewSub
        today.todayNewCollection = result.data.todayNewCollection
        today.todayNewAccessLog = result.data.todayNewAccessLog
        today.todayNewSickMedicalRecords = result.data.todayNewSickMedicalRecords
    }
    
    const debounceList = debounce(req, 500)
    //搜索
    const hanledSearch = () => {
      debounceList()
    }

    // 得到 医生/咨询师 下拉
    const getdoctor = async() => {
      
      let res:any = await getDoctorListAllAPi({})
      if(res.code !== 0) return ElMessage.error('数据获取' + res.msg)
      search.optionsDoctor = res.data
      let res1:any = await getConsultListAllAPi({})
      if(res1.code !== 0) return ElMessage.error('数据获取' + res1.msg)
      search.optionsSecondaryUser = res1.data
    }
    getdoctor()

    // 流程变化
    const handleChangeStatus = async(val:string, RowDataID: number) => {
      let params = {
        id: RowDataID,
        toStatus: val
      }
      let result:any = await useRequest('sick/record/detailToStatus', params, 'POST')
      if(result.code !== 0) return ElMessage.error('数据获取' + result.msg)
        req()
    }

    // 回退状态
    const handleClickReturnOpeation = async(recordId: number) => {
      try{
        let result:any = await useRequest(`sick/record/backDetailToStatus/${recordId}`, {}, 'POST')
        if(result.code !== 0) return ElMessage.error('数据获取' + result.msg)
        req()
        getNumber()
      }catch(e) {
        // ElMessage.error()
        console.log(e)
      }
      
    }

    // 分页
    const handleCurrentChange = (val: number) => {
			search.current = val
      req()
		}
    const handleSizeChange = (val: number) => {
      search.size = val
      req()
		}

    // 去详情
    const onToDetail = (id: number) => {
      useSetAddLog(id)
      router.push(`/allPatientDetails/${id}/patient`)
    }
    // 取消预约
    const personName = ref('')
    // 预约id
    const personID = ref('')
    const subscribeTime = ref('')
    const dialogVisible = ref(false)
    const closeDialog = () => {
      dialogVisible.value = false
    }
    const dialogBtnData = [
      {
        name: '取消',
        func: (data: any) => {
          dialogVisible.value = false
        }
      },
      {
        name: '确定',
        func: (data: any) => {
          request.sendRequest({
            address: 'customer/subscribe/cancelLog',
            params: {
              id: personID.value
            },
            success: (resp: RespData) => {
              if(resp.code !== 0) return ElMessage.error(resp.msg || '获取失败')
              closeDialog()
              req()
            },
            fail: (resp: RespData) => {
              if(resp.code !== 0) return ElMessage.error(resp.msg || '获取失败')
              
            },
            method: "POST",
          })
        }
      },
    ]

    const registerInfo = ref({} as any)
    // 获取挂号信息
    const getRegisterInfo = (id: number) => {
      return new Promise((resolve, reject) => {
          request.sendRequest({
          address: `sick/record/getRecordDetailById/${id}`,
          params: {},
          success: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error('获取挂号信息' + resp.msg)
            registerInfo.value = resp.data
            resolve('')
          },
          fail: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error('获取挂号信息' + resp.msg)
            reject()
          },
          method: "GET",
        })
      })
    }
    const makeanappInfo = ref({} as any)
    // 获取预约信息
    const getMakeanapp = (id: number) => {
      makeanappInfo.value = {}
      return new Promise((resolve, reject) => {
          request.sendRequest({
          address: `sick/record/getSubLogByDetailId/${id}`,
          params: {},
          success: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error('获取预约信息' + resp.msg)
            makeanappInfo.value = resp.data
            resolve('')
          },
          fail: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error('获取预约信息' + resp.msg)
            reject()
          },
          method: "GET",
        })
      })
    }

    const temporaryStatus = ref('')
    const temporaryID = ref()
    // 挂号完改变状态
    const clickRegisterStatus = () => {
      if(title.value === '挂号') {
        handleChangeStatus(temporaryStatus.value, temporaryID.value)
      }
      
    }
    // 患者ID
    const userId = ref()
    // 挂号
    const handleRegister = (RowData: any, val: string) => {
      let personEchoInfo = {
        id: RowData.id,
        detailType: RowData.detailType,
        medicalSources: RowData.medicalSources,
        medicalSourcesType: '',
        masterUserId: RowData.masterUserId,
        secondaryUserId: RowData.secondaryUserId,
        remark: '',
        record: {
          customerId: RowData.customerId
        },
        recordId: ''
      }
      registerInfo.value = personEchoInfo
      if(val) {
        temporaryStatus.value = val
        temporaryID.value = RowData.id
      }

      userId.value = RowData.customerId
      showDrawer.value = true
      title.value = "挂号"
      isADD.value = 'register'

    }
    // 开始治疗
    const startTreatment = (RowData: any, val: string) => {
      let id = RowData.id
      handleChangeStatus(val, id)
      
    }
    // 治疗结束
    const overTreatment = (RowData: any, val: string) => {
      let id = RowData.id
      let name = RowData.customerName
      ElMessageBox.confirm(`确定患者【${name}】,已完成治疗么?`, '确定', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
				
        handleChangeStatus(val, id)
			}).catch(() => {
					ElMessage({
						type: 'info',
						message: '已取消',
					});
      })
      
    }
    // 离店
    const leave = (RowData: any, val: string) => {
      let id = RowData.id
      handleChangeStatus(val, id)
    }

    // 修改挂号
    const editRegister = async (RowData: any) => {
      console.log('修改挂号', RowData)
      let {id, customerId} = RowData
      userId.value = customerId
      await getRegisterInfo(id)

      showDrawer.value = true
      title.value = "修改挂号"
      isADD.value = 'register'
    }
    // 修改预约
    const editAppoiment = async (RowData: any) => {
      let {id} = RowData
      await getMakeanapp(id)

      showDrawer.value = true
      title.value = "修改预约"
      isADD.value = 'makeanapp'
    }
    // 取消预约
    const cancelAppoiment = (RowData: any) => {
      console.log('取消预约')
      personID.value = RowData.subscribeLogId
      personName.value = RowData.customerName
      subscribeTime.value = RowData.startTime
      dialogVisible.value = true
    }
    // 创建新预约
    const addNewAppoiment = (RowData: any) => {
      makeanappInfo.value = {}
      let echoInfo = {
        id: RowData.id,
        customerId: RowData.customerId,
        customerName: RowData.customerName,
        clinicType: RowData.detailType,
        subscribeType: '',
        subscribeTime: '',
        timeLength: '',
        consultantId: '',
        departmentId: '',
        doctorId: RowData.masterUserId,
        nurseId: '',
        remark: '',
        itemIdsShow: [],
        clickType: '新建预约'
      }
      makeanappInfo.value = echoInfo
      showDrawer.value = true
      title.value = "新建预约"
      isADD.value = 'makeanapp'
    }

    // 去 -> 收费(前台划价)
    const goCharge = (RowData: any) => {
      let {customerId} = RowData
      router.push({path:`/allPatientDetails/${customerId}/priceSet`, query: {type: 10, add: 1}})
    }

    // 刷新列表
    const reloadList = () => {
      req()
    }

    // 抽屉 --》 新建预约部分
    const showDrawer = ref(false)
    const title = ref('')
    const isADD = ref('')
    // 打开新建预约
    const saveMakeAnAppointment = () => {
      isADD.value = 'makeanapp'
			title.value = "新建预约"
    }

    const saveAndRegister = () => {
			isADD.value = 'register'
			title.value = "挂号"
		}


    const handlebtn = () => {
      isADD.value = 'add'
			title.value = "个人信息"
    }
    const drawerClose = () => {
      ElMessageBox.confirm('此操作将关闭窗口, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
				showDrawer.value = false
			}).catch(() => {
					ElMessage({
						type: 'info',
						message: '已取消',
					});
      })
    }
    const cancel = () => {
      showDrawer.value = false
    }

    onMounted(() => {
      req()
      getNumber()
      getTodayStatistics()
    })

    return {
      data,
      columns,
      ...toRefs(search),
      today,
      onToDetail,
      inputValue,
      debounce,
      totalNum,
      bagerTitle,
      handleStatusSearch,

      handleCurrentChange,
      handleSizeChange,
      hanledSearch,
      handleChangeStatus,
      clickRegisterStatus,
      handleClickReturnOpeation,
      temporaryID,
      temporaryStatus,

      dialogVisible,
      closeDialog,
      dialogBtnData,
      personName,
      personID,
      subscribeTime,
      userId,

      handleRegister,
      startTreatment,
      overTreatment,
      leave,

      editRegister,
      editAppoiment,
      cancelAppoiment,
      addNewAppoiment,

      showDrawer,
      title,
      isADD,
      saveMakeAnAppointment,
      saveAndRegister,
      handlebtn,
      drawerClose,
      cancel,
      registerInfo,
      makeanappInfo,
      reloadList,
      goCharge,

    }
  }
})
</script>

<style lang="scss" scoped>
.input-2 {
  width: 130px;
}
.select-3 {
  padding-left: 8px;
}

.person-info {
  padding: 10px 0;

  & > span {
    padding-right: 15px;

    .name {
      background: #4094ff;
      color: white;
      padding: 3px 5px;
      border-radius: 4px;
    }
  }
}
</style>